package com.jiuyuan.config.security;

import com.jiuyuan.config.filter.CustomFilter;
import com.jiuyuan.config.filter.CustomUrlDecisionManager;
import com.jiuyuan.entity.Admin;
import com.jiuyuan.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Controller;

/**
 * @program: hrms
 * @description:
 * @author: Feng
 * @create: 2023-02-15 10:57
 **/

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    IAdminService adminService;
    //循环错误
//    @Autowired
//    UserDetailsService userDetailsService;
//    @Autowired
//    PasswordEncoder passwordEncoder;
//    @Autowired
//    JWTAuthenticationFilter jwtAuthenticationFilter;
    @Autowired
    RestAccessDeniedHandler restAccessDeniedHandler;
    @Autowired
    RestAuthenticationEntryPoint restAuthenticationEntryPoint;
    @Autowired
    CustomFilter customFilter;
    @Autowired
    CustomUrlDecisionManager customUrlDecisionManager;

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(
                "/login/**",
                "/css/**",
                "/js/**",
                "/index.html",
                "favicon.ico",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources/**",
                "/v2/api-docs/**",
                "/kaptcha/**",
                "/wsyeb/**"
        );
    }

    @Override
    @Bean
    //走自己的userDetailsService
    protected UserDetailsService userDetailsService() {
        return username -> {

             Admin admin = adminService.getAdminByUsername(username);
             if(null!=admin){
                 admin.setRoles(adminService.getRolesByAdminId(admin.getId()));
                 return admin;
             }
             throw new UsernameNotFoundException("用户名密码有误");
        };
    }

    @Bean
    public JWTAuthenticationFilter jwtAuthenticationFilter(){
        return new JWTAuthenticationFilter();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService())
                .passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/login","logout").permitAll()
                .anyRequest().authenticated()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setAccessDecisionManager(customUrlDecisionManager);
                        object.setSecurityMetadataSource(customFilter);
                        return object;
                    }
                })
                .and()
                //缓存控制
                .headers().cacheControl();

        //jwt过滤器
        http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

        //未登录，权限不足，输出信息
        http.exceptionHandling()
                .accessDeniedHandler(restAccessDeniedHandler)
                .authenticationEntryPoint(restAuthenticationEntryPoint);
    }
}





























